package com.gowhere.controller.system;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.gowhere.controller.BaseServlet;
import com.gowhere.domain.ResultInfo;
import com.gowhere.domain.Role;
import com.gowhere.domain.UserInfo;
import com.gowhere.service.impl.system.UserInfoServiceImpl;
import com.gowhere.service.system.UserInfoService;
import com.gowhere.utils.BeanUtil;
import com.gowhere.utils.MD5Util;
import com.gowhere.utils.MailUtils;
import com.gowhere.utils.UidUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/system/userInfo/*")//你现在自己定yi接收方法ok
public class UserInfoServlet extends BaseServlet {
    public UserInfoService userInfoService = new UserInfoServiceImpl();

    //查询
    public void findByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNum = 1;
        int pageSize = 5;
        String pageNumStr = req.getParameter("page");
        String pageSizeStr = req.getParameter("pageSize");
        if (StringUtils.isNotBlank(pageNumStr)) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (StringUtils.isNotBlank(pageSizeStr))
            pageSize = Integer.parseInt(pageSizeStr);

        List<UserInfo> list = userInfoService.findByPage(pageNum, pageSize);
        PageInfo<UserInfo> pageInfo = new PageInfo<>(list);
        req.setAttribute("page", pageInfo);
        req.getRequestDispatcher("/pages/system/user-list.jsp").forward(req, resp);
    }

    //新增
    public void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserInfo userInfo = BeanUtil.fillBean(req, UserInfo.class);
        userInfoService.save(userInfo);
        req.getRequestDispatcher("/system/userInfo/findByPage").forward(req, resp);
    }

    //详情
    public void turnToEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        UserInfo userInfo = userInfoService.findById(id);
        req.setAttribute("userInfo", userInfo);
        req.getRequestDispatcher("/pages/system/user-show.jsp").forward(req, resp);
    }

    //更改角色页面回显
    public void turnToEdit1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
//        UserInfo userInfo = userInfoService.findById(id);
        List<Role> list = userInfoService.findRoleUserUid(id);

        req.setAttribute("uid", id);
        req.setAttribute("roleList",list);

        req.getRequestDispatcher("/pages/system/user-role-add.jsp").forward(req, resp);
    }

    public void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String ids = req.getParameter("ids");
        boolean flag = userInfoService.delete(ids);
        req.getRequestDispatcher("/system/userInfo/findByPage").forward(req, resp);
    }
    public void addRoleToUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("userId");
        System.out.println("userId");
        String[] roleIds = req.getParameterValues("ids");

        userInfoService.addRoleToUser(userId, roleIds);
        req.getRequestDispatcher("/system/userInfo/findByPage").forward(req, resp);
    }
    //模糊查询
    public void likeName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//可以吗,你把URL改正确

        req.getRequestDispatcher("/system/userInfo/findByPage").forward(req, resp);

    }


    protected void turnStatus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String uid = req.getParameter("uid");
        String status = req.getParameter("status");

        if("1".equals(status)){
            status ="0";
        }else {
            status="1";
        }
        userInfoService.turnStatus(uid,status);

        resp.getWriter().write(" ");
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //通过BeanUtils来封装用户对象
        UserInfo userInfo = BeanUtil.fillBean(req, UserInfo.class);
        System.out.println(userInfo.getUsername()+userInfo.getPassword());

        //2.1获取用户输入验证码
        String check = req.getParameter("check");
        //获取session中的验证码
        String check_server = (String) req.getSession().getAttribute("CHECKCODE_SERVER");
        req.getSession().removeAttribute("CHECKCODE_SERVER");
        //调用service层，将封转好的的数据传给业务逻辑层
        UserInfo u = userInfoService.login(userInfo);

        ResultInfo info = new ResultInfo();   //用于封装后端返回前端数据对象

        // 4.判断用户对象是否为null
        if (u == null) {
            //用户名或密码错误
            info.setFlag(false);
            info.setErrorMsg("用户名密码或错误");
        }
        // 5.判断用户是否激活
        if (u != null && u.getStatus()!=1) {
            //用户尚未激活
            info.setFlag(false);
            info.setErrorMsg("账户已被注销");
        }

        // 5.1判断验证码
        if (u != null && u.getStatus()==1 && !check_server.equalsIgnoreCase(check)) {
            //用户尚未激活
            info.setFlag(false);
            info.setErrorMsg("验证码错误!");
        }
        System.out.println(info);
        // 6.判断登录成功
        if (u != null && u.getStatus()==1 && check_server.equalsIgnoreCase(check)) {
            u.setPassword(userInfo.getPassword());
            //获取记住密码参数
            String rb = req.getParameter("rb");
            String ck = req.getParameter("ck");
            System.out.println(ck);
            //创建相应的cookie对象
            Cookie username = new Cookie("username", u.getUsername());
            Cookie password = new Cookie("password", u.getPassword());
            Cookie uname = new Cookie("uname", u.getUsername());
            Cookie pword = new Cookie("pword", u.getPassword());
            //如果选择了记住密码，即参数为1，则设置cookie存活时间为一小时，否则设为0
//            boolean flag = false;
            if ("1".equals(rb)) {
                username.setMaxAge(3600);
                password.setMaxAge(3600);
//                flag = true;
            } else {
                username.setMaxAge(0);
                password.setMaxAge(0);
            }
            if ("1".equals(ck)) {
                uname.setMaxAge(3600);
                pword.setMaxAge(3600);
            } else {
                uname.setMaxAge(0);
                pword.setMaxAge(0);
            }
            //将cookie路径设为根路径，防止路径出错
            username.setPath("/");
            password.setPath("/");
            uname.setPath("/");
            pword.setPath("/");
            //添加到域中
            resp.addCookie(username);
            resp.addCookie(password);
            resp.addCookie(uname);
            resp.addCookie(pword);
            //登陆成功将用户信息添加到session中，下次自动登录
            req.getSession().setAttribute("user", u);
            //用户登录成功
            info.setFlag(true);
//            req.getSession().setAttribute("rb", flag);
        }//响应数据
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(info);
        resp.setContentType("text/json;charset=UTF-8");
        String s = mapper.writeValueAsString(info);
        resp.getWriter().write(s);

    }

    private void exit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //退出登录，移除参数，注销session
        req.getSession().removeAttribute("user");
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath() + "/pages/login.jsp");
    }

    /**
     *发送邮箱验证码
     */
    public void sendVd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String s = request.getParameter("username");

        UserInfo u = userInfoService.findByName(s);
        String uuid = UidUtil.getUid();
        System.out.println(uuid);
        String content=  "【验证码】: "+uuid;
        request.getSession().setAttribute("v",uuid);
        MailUtils.sendMail(u.getEmail(),content,"修改密码");
    }

    /**
     * 邮箱验证码校验
     */
    public void validate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //验证校验
        String check = request.getParameter("check");
        //从sesion中获取验证码
        HttpSession session = request.getSession();
        String v = (String) session.getAttribute("v");
        //比较
        Map<String,String> map = new HashMap<String, String>();
        if(v != null && v.equalsIgnoreCase(check)) {
            //验证码错误
            map.put("ok","验证码正确");
            session.removeAttribute("v");//为了保证验证码只能使用一次
        }else {
            map.put("error","验证码有误");
        }
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getWriter(),map);
    }

    /**
     * 用户名校验(存在正确)
     */
    public void confirmUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        UserInfo user = userInfoService.findByName(username);

        Map<String,String> map = new HashMap<String, String>();
        if (user != null){
            map.put("ok","用户名正确!");
        }else{
            map.put("error","用户名不存在!");
        }

        response.setContentType("application/json;charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getWriter(),map);
    }

    /**
     * 跳转到修改页面
     */
    public void jump(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        request.getSession().setAttribute("username",username);
        response.sendRedirect(request.getContextPath()+"/pages/password_continue.jsp");
    }

    /**
     *确认密码
     */
    public void confirmPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String password = request.getParameter("password");
        String c_password = request.getParameter("c_password");
        System.out.println(password);

        ResultInfo info = new ResultInfo();
        if(password!=null && password.equals(c_password)){
            info.setFlag(true);
        }else {
            info.setFlag(false);
            info.setErrorMsg("密码错误!");
        }
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),info);
    }

    /**
     *修改密码
     */
    public void password(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取用户名和密码数据
        Map<String, String[]> map = req.getParameterMap();
        // 2.封装User对象
        UserInfo user = new UserInfo();
        try {
            BeanUtils.populate(user,map);
            String s = MD5Util.md5(user.getPassword());
            user.setPassword(s);
        } catch (Exception e) {

        }
        System.out.println(user.getUsername()+user.getPassword());
        userInfoService.password(user);

        //移除参数，注销session
        req.getSession().removeAttribute("user");
        req.getSession().invalidate();
        //4.成功重定向到成功页面
        resp.sendRedirect(req.getContextPath()+"/pages/login.jsp");
    }

}

